package com.lkd.job;

import com.lkd.common.VMSystem;
import com.lkd.entity.UserEntity;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class TaskInitJob {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 每日工单量列表初始化
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) throws Exception{
        //查询用户列表
        List<UserEntity> userEntities = userService.list();
        //第一次测试用参数
        int plusDay = "0".equals(param)? 0 : 1;
        //构建数据（zset）
        for (UserEntity userEntity : userEntities) {
            Long regionId = userEntity.getRegionId();//区域id
            String roleCode = userEntity.getRoleCode();//人员编码
            if (VMSystem.USER_OPERATOR.equals(roleCode) || VMSystem.USER_REPAIRER.equals(roleCode)){
                //以固定字符串（前缀）+日期+区域+工单类别（运营/运维）为大key，以人员id做小key，过期时间为2天。
                String key = VMSystem.REGION_TASK_KEY_PREF
                        + LocalDate.now().plusDays(plusDay).format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                        + regionId
                        + roleCode;
                redisTemplate.opsForZSet().add(key , userEntity.getId() , 0);
                redisTemplate.expire(key , Duration.ofDays(2));
            }
        }



        return ReturnT.SUCCESS;
    }
}
